package com.example.parallelandroid;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;

public class PermissionActivity extends AppCompatActivity {

    private Intent intent;
    private final int REQUEST_PERMISSION = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission);
        intent = new Intent(this, SplashActivity.class);
        // 判断是否有权限
        checkPermission();
    }

    private void checkPermission() {
        String[] permission = {Manifest.permission.ACTIVITY_RECOGNITION};
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int res = ContextCompat.checkSelfPermission(this, permission[0]);
            if (res == PackageManager.PERMISSION_GRANTED) {
                initStepService();
                startActivity(intent);
            } else {
                ActivityCompat.requestPermissions(this, permission, REQUEST_PERMISSION);
            }
        } else {
            initStepService();
            startActivity(intent);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initStepService();
                startActivity(intent);
            } else {
                System.exit(0);
            }
        }
    }

    private void initStepService() {
        Intent intent = new Intent(this, StepService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
    }
}